package soria.cabinet.security;

import java.io.*;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Map;

public class Device {
    //公钥
    private static final String PUBLIC_KEY;
    //私钥
    private static final String PRIVATE_KEY;
    //AES密钥
    private static final String AES_KEY;

    public static String getPublicKey() {
        return PUBLIC_KEY;
    }

    /**
     * 通过公钥获取加密后的AES密钥
     * @param key RSA公钥
     * @return 加密后的AES密钥
     */
    public static String getSecretKey(String key){
        return RSA.encrypt(AES_KEY,key);
    }

    static {
        Map<String, String> map = RSA.generateKey();
        PUBLIC_KEY = map.get("publicKey");
        PRIVATE_KEY = map.get("privateKey");
        AES_KEY = AES.generateKey();
    }

    /**
     * 获取本地主机的MAC地址
     *
     * @return MAC地址
     */
    protected static byte[] getMAC() {
        try {
            InetAddress ip = InetAddress.getLocalHost();
            NetworkInterface net = NetworkInterface.getByInetAddress(ip);
            return net.getHardwareAddress();
        } catch (SocketException | UnknownHostException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 对文件进行加密或解密处理
     *
     * @param operateFile 待处理文件
     * @param pattern     处理模式，ENCRYPT为加密模式，DECRYPT为解密模式
     * @param secretKey   密钥，只传入一个，多个只取第一个
     */
    public static void fileHandle(File operateFile, Pattern pattern, String... secretKey) {
        try {
            byte[] data;
            //输入流
            InputStream input = new FileInputStream(operateFile);
            BufferedInputStream bufferedInput = new BufferedInputStream(input);
            //读取文件内容
            data = bufferedInput.readAllBytes();
            bufferedInput.close();
            if (operateFile.delete()) {
                //输出流
                OutputStream output = new FileOutputStream(operateFile);
                BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);
                //加密或解密
                if (pattern == Pattern.ENCRYPT) {
                    bufferedOutput.write(AES.encrypt(data, AES_KEY));
                } else if (pattern == Pattern.DECRYPT) {
                    bufferedOutput.write(AES.decrypt(data, secretKey[0]));
                }
                bufferedOutput.close();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 解密AES密钥
     * @param secretKey 待解密的密钥
     * @return 解密后的密钥
     */
    public static String decryptKey(String secretKey){
        if(!secretKey.isEmpty()){
            return RSA.decrypt(secretKey, PRIVATE_KEY);
        }
        return null;
    }
}